package com.test.feishu;

import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

@Component
public class FeiShuSendMsgUtil {

    //获取签名
    private static String GenSign(String secret, int timestamp) throws Exception {
        //把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + secret;
        //使用HmacSHA256算法计算签名
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64.encodeBase64(signData));
    }

    public static void main(String[] args) {
        try {
            int timestamp = (int) (System.currentTimeMillis() / 1000);
            String sign = GenSign("RqehG5uc8czU68WtpcuFkh", timestamp);
            String msg = "客户789已销卡456失败，请及时处理";

            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\"timestamp\": \"" + timestamp + "\",\"sign\": \"" + sign + "\",\"msg_type\":\"text\",\"content\":{\"text\":\"" + msg + "<at user_id=\\\"all\\\">所有人</at>\"}}");
            Request request = new Request.Builder()
                    .url("https://open.feishu.cn/open-apis/bot/v2/hook/c92c03e0-077e-49d8-868c-5ab42de7e456")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
